<template>
  <div class="p-2 addListBox">
    <div v-if="route.query.type == 'add'" style="margin: 20px 10px;font-weight: 600;font-size: 26px;display:flex;align-items: center;">
      添加车位管理费缴费记录
    </div>
    <div v-else style="margin: 20px 10px;font-weight: 600;font-size: 26px;display:flex;align-items: center;">修改车位管理费缴费记录</div>
    <el-card shadow="never">
      <el-table v-loading="loading" :data="assetCWList">
        <el-table-column align="center">
          <template #header>
            <div>小区名称 <span style="color: #ff0000;">*</span></div>
            <!-- <el-switch
                v-model="xmswitchType"
                class="ml-2"
                inline-prompt
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                active-text="整体一致"
                inactive-text="逐个修改"
                disabled
              /> -->
          </template>
          <template #default="scope">
            <el-select
              class="slese"
              @visible-change="xmhandleVisibleChange"
              v-model="scope.row.projectId"
              placeholder="请选择项目"
              ref="selectRef"
              @change="xmchanged($event,scope.row)"
              v-if="route.query.type == 'add'"
            >
              <el-option class="xmDropdown" v-for="item in xmOptions" :key="item.id" :label="item.projectName" :value="item.id" />
              <p class="el-select-dropdown__empty" v-show="loadingmore">加载中</p>
            </el-select>
            <span v-else> {{scope.row.projectName}} </span>
          </template>
        </el-table-column>

        <el-table-column align="center">
          <template #header>
            <div>房屋号 <span style="color: #ff0000;">*</span></div>
          </template>
          <template #default="scope">
            <el-select
              class="slese"
              @visible-change="househandleCWVisibleChange($event,scope)"
              v-model="scope.row.houseId"
              placeholder="请选择房屋"
              ref="selectRef"
              filterable
              v-if="route.query.type == 'add'"
              :filter-method="getHouseHomeList"
            >
              <el-option
                class="parkCWHousDropdown"
                v-for="item in houseCWCostList"
                :key="item.houseId"
                :label="item.houseNumber"
                :value="item.houseId"
              />
              <p class="el-select-dropdown__empty" v-show="loadingCWHouseMore">加载中</p>
            </el-select>
            <el-input v-else v-model="scope.row.houseNumber" placeholder="请输入房屋号" disabled />
          </template>
        </el-table-column>
        <el-table-column align="center">
          <template #header>
            <div>车位号 <span style="color: #ff0000;">*</span></div>
          </template>
          <template #default="scope">
            <el-input maxlength="60" v-model="scope.row.garageNumber" placeholder="请输入车位号" />
          </template>
        </el-table-column>
        <el-table-column align="center">
          <template #header>
            <div>车牌号 <span style="color: #ff0000;">*</span></div>
          </template>
          <template #default="scope">
            <el-input maxlength="60" v-model="scope.row.garageCarNumber" placeholder="请输入车牌号" />
          </template>
        </el-table-column>

        <el-table-column align="center">
          <template #header>
            <div>车位管理费 <span style="color: #ff0000;">*</span></div>
            <!-- <el-switch
                  v-model="parkCostSwitchType"
                  class="ml-2"
                  inline-prompt
                  style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                  active-text="整体一致"
                  inactive-text="逐个修改"
                /> -->
          </template>
          <template #default="scope">
            <el-input
              type="number"
              v-model="scope.row.garageManagementCost"
              @input="checkGarageManagementCost($event,scope.row)"
              placeholder="请输入车位管理费"
            />
          </template>
        </el-table-column>
        <el-table-column align="center">
          <template #header>
            <div>
              是否开具发票 <br />
              <el-switch
                v-model="isNeedInvoiceType"
                class="ml-2"
                inline-prompt
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                active-text="整体一致"
                inactive-text="逐个修改"
              />
            </div>
          </template>
          <template #default="scope">
            <el-select
              class="slese"
              v-model="scope.row.isNeedInvoice"
              placeholder="请选择"
              ref="selectRef"
              @change="isNeedInvoiceChanged($event,scope.row)"
              v-if="routeType == 'add'"
            >
              <el-option v-for="item in is_need_invoice" :key="item.value" :label="item.label" :value="item.value" />
              <p class="el-select-dropdown__empty" v-show="loadingmore">加载中</p>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" width="300px">
          <template #header>
            <div>
              <div>车位管理费周期 <span style="color: #ff0000;">*</span></div>
              <el-switch
                v-model="timeRangeCWSwitchType"
                class="ml-2"
                inline-prompt
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                active-text="整体一致"
                inactive-text="逐个修改"
              />
            </div>
          </template>
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.garageManagementStartDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择开始日期"
              @change="startTimer($event,scope.row)"
            ></el-date-picker>
            <span style="margin:0 6px">至</span>
            <el-date-picker
              v-model="scope.row.garageManagementEndDate"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择结束日期"
              @change="endTimer($event,scope.row)"
            ></el-date-picker>
          </template>
        </el-table-column>

        <el-table-column v-if="routeType == 'add'" label="操作" align="center" class-name="small-padding fixed-width" width="50px">
          <template #default="scope">
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="assetCWList = assetCWList.filter(item => item != scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <div style="display: flex;justify-content: center;margin-top: 20px;">
      <el-button v-if="route.query.type == 'add'" type="primary" icon="Plus" @click="addLine">追加一条</el-button>
      <el-button v-if="route.query.type == 'add'" type="success" icon="Position" @click="handleQuery">提交全部</el-button>
      <el-button v-else type="success" icon="Position" @click="handleQuery">提交修改</el-button>
      <el-button @click="goBack">返 回</el-button>
    </div>
  </div>
</template>

<script setup name="AssetCataAdd" lang="ts">
import { getAssetOutboundRecords, addAssetOutboundRecords, updateAssetOutboundRecords } from '@/api/business/assetOutboundRecords/index';


//   有用的
import { listCost, getCost, delCost, addCost, updateCost } from '@/api/business/parkingLotCost';
import { listHouseInfo } from '@/api/business/houseInfo';
import { ProjectQuery } from '@/api/business/project/types';
import { listProject } from '@/api/business/project';
import { HouseCostVO } from '@/api/business/houseCost/types';
import { ref } from 'vue'
import { listStandard } from '@/api/business/standard';
import { addDays } from 'date-fns';
import { ar } from 'element-plus/es/locale';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { charge_category } = toRefs<any>(proxy?.useDict('charge_category'));
const { is_need_invoice } = toRefs<any>(proxy?.useDict('is_need_invoice'));
const route = useRoute()

const routeType = ref('add');
const loading = ref(true);
const assetCWList = ref([]);
// const xmswitchType = ref(true);
// const parkCostSwitchType = ref(true);
const timeRangeCWSwitchType = ref(true);
const isNeedInvoiceType = ref(true);
const xmOptions = ref()
const xmtotal = ref(0);
const xmqueryParams = ref<ProjectQuery>({
    pageNum: 1,
    pageSize: 10,
    isExit: 0
})
const loadingmore = ref(false)
const houseCWCostList = ref<HouseCostVO[]>([]);
const CWtotal = ref(0)
const queryParamsCWFW = ref({
  pageNum: 1,
  pageSize: 10,
  projectId: undefined,
  houseNumber:undefined,
});
const loadingCWHouseMore = ref(false)
const listItem = {
    projectId:'',
    houseId:'',
    garageNumber: '',
    garageCarNumber: '',
    garageManagementCost: '',
    garageManagementStartDate: '',
    garageManagementEndDate: '',
    isNeedInvoice:'0'
}
const queryParamsSF = ref({
  pageNum: 1,
  pageSize: 10,
  chargeCategory: undefined
});
const cWParkHouseIndex=ref(0)
const cwglfValue=ref(0)
const errRowIndexList=ref([])

/** 查询项目管理列表 */
const getList = async () => {
    loading.value = true;
    const xm = await listProject(xmqueryParams.value);
    xmOptions.value = xm.rows
    xmtotal.value = xm.total;
    queryParamsSF.value.chargeCategory = charge_category.value[4].value
    const res = await listStandard(queryParamsSF.value);
    listItem.garageManagementCost = res.rows[0].chargeMoney
    cwglfValue.value = res.rows[0].chargeMoney
    loading.value = false;
}

  // 追加一条
const addLine = () => {
    if(assetCWList.value.length > 0) {
        // xmswitchType.value?listItem.projectId=assetCWList.value[0].projectId:''
        // parkCostSwitchType.value?listItem.garageManagementCost=assetCWList.value[0].garageManagementCost:''
        timeRangeCWSwitchType.value?listItem.garageManagementStartDate=assetCWList.value[0].garageManagementStartDate:''
        timeRangeCWSwitchType.value?listItem.garageManagementEndDate=assetCWList.value[0].garageManagementEndDate:''
        isNeedInvoiceType.value?listItem.isNeedInvoice=assetCWList.value[0].isNeedInvoice:undefined
        listItem.garageManagementCost=cwglfValue.value
        listItem.projectId=assetCWList.value[0].projectId
      }
    assetCWList.value.push(JSON.parse(JSON.stringify(listItem)))
}

const xmchanged = async (id,row)=> {
    xmOptions.value.forEach(element => {
      if(element.id == id) {
        row.projectName = element.projectName
        row.projectId = element.id
        assetCWList.value.forEach(item => {
          item.projectName = row.projectName
          item.projectId = row.projectId
        })
        /* if(xmswitchType.value) {
          assetCWList.value.forEach(item => {
            item.projectName = row.projectName
            item.projectId = row.projectId
          })
        } */
      }
    });
    // form.value.houseNumber = undefined
    queryParamsCWFW.value.projectId = id
    const res = await listHouseInfo(queryParamsCWFW.value);
    houseCWCostList.value = res.rows
    CWtotal.value = res.total
}

const checkGarageManagementCost = (value,row) => {
    if (value<=0) {
        ElMessage.warning('车位管理费不能小于等于0')
    }
    // row.garageManagementCost = row.garageManagementCost
    /* if(parkCostSwitchType.value) {
        assetCWList.value.forEach(item => {
            item.garageManagementCost = row.garageManagementCost
        })
    } */
}

const startTimer = (value,row) => {
    row.garageManagementStartDate = value
    if (row.garageManagementStartDate) {
        let timer = addDays(row.garageManagementStartDate, 365)
        let date = new Date(timer);
        let y = date.getFullYear();
        let m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        let d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        row.garageManagementEndDate = y + '-' + m + '-' + d + ' 00:00:00'
    } else {
        row.garageManagementEndDate = undefined
    }
    if (timeRangeCWSwitchType.value) {
        assetCWList.value.forEach(item => {
            item.garageManagementStartDate = row.garageManagementStartDate
            item.garageManagementEndDate = row.garageManagementEndDate
        })
    }
}

const endTimer = (value,row) => {
    row.garageManagementEndDate = value
    if (row.garageManagementEndDate <= row.garageManagementStartDate) {
        startTimer(row.garageManagementStartDate,row)
        ElMessage.warning('结束时间不能小于开等于始时间');
    }
    if (timeRangeCWSwitchType.value) {
        assetCWList.value.forEach(item => {
            item.garageManagementStartDate = row.garageManagementStartDate
            item.garageManagementEndDate = row.garageManagementEndDate
        })
    }
}


const hasEmptyValue = (arr) => {
  let newArr = JSON.parse(JSON.stringify(arr))
  newArr = newArr.map(obj => {
    delete obj.garageArea;
    delete obj.garageCategory;
    delete obj.garageCollectionDate;
    delete obj.garageId;
    delete obj.remark;
    return obj;
  });
  return !newArr.every(obj => Object.values(obj).every(value => value != null && value !== '' && value !== undefined));
}

const validateArray = (arr) =>{
  let falseList = []
  arr.forEach(function(item,index) {
    if (item.garageManagementCost <= 0) {
      let errObj = { errIndex:index }
      falseList.push(errObj)
    }
  });
  return falseList.length>0?true:false
}

const checkValueLenth = (arr) =>{
  let hasFalseList = []
  arr.forEach(function(item,index) {
    if (item.garageManagementCost>99999999) {
      hasFalseList.push(index)
    }
  });
  return hasFalseList.length>0?true:false
}

const hasDuplicateName = (arr) =>{
  return arr.some((item, index) =>
    arr.slice(0, index).some(otherItem => item.houseId === otherItem.houseId)
  );
}

const hasNoEmptyValues = () => {
    let flag = true
    let checkValue = hasEmptyValue(assetCWList.value)
    let hasLittleValue = validateArray(assetCWList.value)
    let checkLength = checkValueLenth(assetCWList.value)
    if(route.query.type == 'edit') {
      if (checkValue) {
          flag?ElMessage.error('请将信息填写完成！'):''
          flag = false
      } else if(hasLittleValue) {
          flag?ElMessage.error('车位管理费不能小于等于0!'):''
          flag = false
      } else if(checkLength) {
          flag?ElMessage.error('车位管理费不合理!'):''
          flag = false
      } else {
          flag = true
      }
    }else {
      if (checkValue) {
          flag?ElMessage.error('请将信息填写完成！'):''
          flag = false
      } else if(hasLittleValue) {
        flag?ElMessage.error('车位管理费不能小于等于0!'):''
        flag = false
      } else if(checkLength) {
        flag?ElMessage.error('车位管理费不合理!'):''
        flag = false
      } else {
          flag = true
      }
    }
    return flag
  }

const tableRowClassName = ({row,rowIndex,}: {row: any,rowIndex: number}) => {
  if (route.query.type == 'edit') return
  for (var i = 0; i < errRowIndexList.value.length; i++) {
    if (errRowIndexList.value[i].errIndex == rowIndex) {
      return 'warning-row'
    }
  }
  return ''
}

  // 提交全部
const handleQuery = async () => {
  // errRowIndexList.value = []
  if(hasNoEmptyValues()) {
      if(route.query.type == 'edit') {
          await updateCost({'garageCostListBo':assetCWList.value}).then(() =>  {proxy?.$modal.msgSuccess("修改成功");});
          await goBack()
      }else {
          await addCost({'garageCostListBo':assetCWList.value}).then(() =>  {proxy?.$modal.msgSuccess("新增成功");});
          await goBack()
      }
  }
}

  /** 返回 */
  const goBack = () =>{
    const obj = { path: "/costManagement/parkingLotCost" };
    proxy?.$tab.closeOpenPage(obj);
  }

  const xmhandleVisibleChange = (visible: any) => {    
    try {
      if (visible) {
        // 如果下拉框显示
        let xmDropdown: any = document.getElementsByClassName('xmDropdown')[0].parentElement.parentElement
        // 监听下拉框滚动事件
        xmDropdown.addEventListener('scroll', xmloadNextPage)
      } else {
        // 如果下拉框隐藏
        let xmDropdown: any = document.getElementsByClassName('xmDropdown')[0].parentElement.parentElement
        // 移除下拉框滚动事件监听
        xmDropdown.removeEventListener('scroll', xmloadNextPage)
      }
    } catch (error) {}
  }

  const xmloadNextPage = async () => {
    // let xmDropdown: any = document.querySelector('.el-select-dropdown__wrap');
    let xmDropdown: any = document.getElementsByClassName('xmDropdown')[0].parentElement.parentElement;
    // 判断下拉框是否触底
    if (xmDropdown.scrollTop + xmDropdown.clientHeight >= xmDropdown.scrollHeight - 2) {
      loadingmore.value = true
      if (xmOptions.value.length + 1 <= xmtotal.value && loadingmore.value) {
        xmqueryParams.value.pageNum ++
        const res = await listProject(xmqueryParams.value)
        xmOptions.value.length + 1 <= xmtotal.value?xmOptions.value.push(...res.rows):''
        loadingmore.value = false
      }else{
        loadingmore.value = false
        xmDropdown.removeEventListener('scroll', xmloadNextPage)
      }
    }
  }

  /**房屋号下拉滚动加载 */
  const househandleCWVisibleChange = (visible: any,scope:any) => {
    cWParkHouseIndex.value = scope.$index
    try {
      if (visible) {
        // 如果下拉框显示
        let length = (document.getElementsByClassName('parkCWHousDropdown').length)/assetCWList.value.length*cWParkHouseIndex.value
        let parkCWHousDropdown: any = document.getElementsByClassName('parkCWHousDropdown')[length].parentElement.parentElement
        // 监听下拉框滚动事件
        parkCWHousDropdown.addEventListener('scroll', houseCWLoadNextPage)
      } else {
        // 如果下拉框隐藏
        let length = (document.getElementsByClassName('parkCWHousDropdown').length)/assetCWList.value.length*cWParkHouseIndex.value
        let parkCWHousDropdown: any = document.getElementsByClassName('parkCWHousDropdown')[length].parentElement.parentElement
        // 移除下拉框滚动事件监听
        parkCWHousDropdown.removeEventListener('scroll', houseCWLoadNextPage)
      }
    } catch (error) {}
  }
const houseCWLoadNextPage = async () => {
    // let tzDropdown: any = document.querySelector('.el-select-dropdown__wrap');
    let length = (document.getElementsByClassName('parkCWHousDropdown').length)/assetCWList.value.length*cWParkHouseIndex.value
    let parkCWHousDropdown: any = document.getElementsByClassName('parkCWHousDropdown')[length].parentElement.parentElement;
    // 判断下拉框是否触底
    if (parkCWHousDropdown.scrollTop + parkCWHousDropdown.clientHeight >= parkCWHousDropdown.scrollHeight - 2) {
      loadingCWHouseMore.value = true
      if (houseCWCostList.value.length + 1 <= CWtotal.value && loadingCWHouseMore.value) {
        queryParamsCWFW.value.pageNum ++
        const res = await listHouseInfo(queryParamsCWFW.value)
        houseCWCostList.value.length + 1   <= CWtotal.value?houseCWCostList.value.push(...res.rows):''
        loadingCWHouseMore.value = false
      }else{
        loadingCWHouseMore.value = false
        parkCWHousDropdown.removeEventListener('scroll', houseCWLoadNextPage)
      }
    }
  }

const getHouseHomeList = async (value: string) => {
  if (value) {
    queryParamsCWFW.value.houseNumber = value
    const house = await listHouseInfo(queryParamsCWFW.value);
    houseCWCostList.value = house.rows
    CWtotal.value = house.total
  }
}
const isNeedInvoiceChanged = (id:string,row:any) => {
  if(isNeedInvoiceType.value) {
    assetCWList.value.forEach(item => {
        item.isNeedInvoice = row.isNeedInvoice
      })
    }
}
  onMounted(async () => {
    await getList()
    route.query.type == 'edit' ? sessionStorage.setItem("searchCKFlag", '0') : sessionStorage.setItem("searchCKFlag", '1')
    if(route.query.type == 'edit') {
        const res = await getCost(route.query.garageCostId);
        assetCWList.value = [res.data]
        /* assetCWList.value.forEach( element => {
          element.CKWYF = listItem.CKWYF
        }) */
    }else{
      addLine()
    }
  })
</script>
<style>
.addListBox .el-date-editor  {
  --el-date-editor-width: 122px;
}
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-danger-light-3);
}
</style>
